package com.wusuowei.oauthserver.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wusuowei.oauthserver.ucenter.feignclient.CheckCodeClient;
import com.wusuowei.oauthserver.ucenter.mapper.UserMapper;
import com.wusuowei.oauthserver.ucenter.model.dto.UserExt;
import com.wusuowei.oauthserver.ucenter.model.po.User;
import com.wusuowei.oauthserver.ucenter.model.vo.AuthParamsVo;
import com.wusuowei.oauthserver.ucenter.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @description 邮件认证
 * @author LGY
 * @date 2023/04/11 18:57
 * @version 1.0.0
 */
@Service("email_authservice")
public class EmailServiceImpl implements AuthService {


    @Autowired
    UserMapper userMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    CheckCodeClient checkCodeClient;

    @Override
    public UserExt execute(AuthParamsVo authParamsVo) {
        //得到验证码
        String checkcode = authParamsVo.getCheckcode();
        String emailkey = authParamsVo.getEmail();
        if(StringUtils.isBlank(emailkey) || StringUtils.isBlank(checkcode)){
            throw new RuntimeException("验证码为空");

        }
        //校验验证码,请求验证码服务进行校验
        Boolean result = checkCodeClient.verify(emailkey, checkcode);
        if(result==null || !result){
            throw new RuntimeException("验证码错误");
        }

        //邮箱
        String email = authParamsVo.getEmail();
        //从数据库查询用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getEmail, email).or().eq(User::getUsername,email));
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        user.setLoginDate(LocalDateTime.now());
        userMapper.updateById(user);
        UserExt xcUserExt = new UserExt();
        BeanUtils.copyProperties(user,xcUserExt);
        return xcUserExt;
    }

}
